import { Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { InventoryEntity } from '../entity/inventory';
import { divide, times } from '../../../comm/math';

@Provide()
export class InventoryService extends BaseService {
  @InjectEntityModel(InventoryEntity)
  entity: Repository<InventoryEntity>;

  async add(data) {
    const records = data.map(item => {
      const box_gauge = item.box_gauge || 0;
      const product_quantity = item.product_quantity || 0;
      // 库存量
      const remaining_inventory_quantity = times(box_gauge, product_quantity);
      // 单价
      item.unit_price = divide(item.buying_price, box_gauge);
      return { ...item, remaining_inventory_quantity };
    });

    await this.entity.save(records);
    return data.id;
  }

  async upsert(data) {
    return await this.entity.upsert(data, {
      conflictPaths: ['id'],
    });
  }
}
